import { http, HttpResponse } from 'msw'

const variables = [
  { key: 'name', name: '姓名', type: 'text', optional: false, maxLength: 50 },
  { key: 'age', name: '年龄', type: 'number', optional: true },
  { key: 'gender', name: '性别', type: 'dropdown', optional: false, options: ['男', '女', '其他'] }
]

export const handlers = [
  http.get('/mock/variables', () => {
    return HttpResponse.json({
      code: 200,
      data: variables,
      message: 'Success'
    })
  }),

  http.post('/mock/variables', async ({ request }) => {
    const newVariable = await request.json()
    variables.push(newVariable)
    return HttpResponse.json({
      code: 201,
      data: newVariable,
      message: 'Variable added successfully'
    })
  }),

  http.put('/mock/variables/:key', async ({ params, request }) => {
    const updatedVariable = await request.json()
    const index = variables.findIndex((v) => v.key === params.key)
    if (index !== -1) {
      variables[index] = updatedVariable
      return HttpResponse.json({
        code: 200,
        data: updatedVariable,
        message: 'Variable updated successfully'
      })
    }
    return new HttpResponse(
      JSON.stringify({
        code: 404,
        message: 'Variable not found'
      }),
      { status: 404 }
    )
  }),

  http.delete('/mock/variables/:key', ({ params }) => {
    const index = variables.findIndex((v) => v.key === params.key)
    if (index !== -1) {
      variables.splice(index, 1)
      return HttpResponse.json({
        code: 200,
        message: 'Variable deleted successfully'
      })
    }
    return new HttpResponse(
      JSON.stringify({
        code: 404,
        message: 'Variable not found'
      }),
      { status: 404 }
    )
  })
]
